package org.e_gold.dao.impl;

import java.util.Date;
import java.util.List;

import org.e_gold.dao.GenericDAO;
import org.e_gold.model.ValueObject;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

public abstract class AbstractGenericDAO<T extends ValueObject> implements GenericDAO<T> {

    private Class<T> type;

    @Autowired
    private SessionFactory sessionFactory;

    protected Session getCurrentSession() {

        return sessionFactory.getCurrentSession();
    }

    public AbstractGenericDAO(Class<T> type) {

        this.type = type;
    }

    @Override
    @Transactional
    public T insert(T t) {

        t.setInsertTimeStamp(new Date());
        t.setModifyTimeStamp(new Date());
        getCurrentSession().save(t);
        return t;
    }

    @Override
    @Transactional
    public void delete(T t) {

        getCurrentSession().delete(t);
    }

    @Override
    @Transactional
    public T update(T t) {

        t.setModifyTimeStamp(new Date());
        getCurrentSession().update(t);
        return t;
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional
    public T findOne(Long id) {

        return (T) getCurrentSession().get(type, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional
    public List<T> findAll() {

        Criteria criteria = getCurrentSession().createCriteria(type);
        return criteria.list();
    }

}
